function [] = latexTable( table, filename, metaheader)
% Create LaTeX table from MATLAB table containing arbitrary strings
% 
%
% INPUTS
%       table: MATLAB table object
%       filename: Path to print to file
%       metaheader: Header for any elements spanning multiple columns
%
%

% Table metadata
numDataRows = size(table,1);
numDataCols = size(table,2);

colHeaders = table.Properties.VariableDescriptions;
untHeaders = table.Properties.VariableUnits;
% colHeaders = table.Properties.VariableNames;
rowNames = table.Properties.RowNames;

% Formatting
format = ['%15s',repmat('\t%s',1,numDataCols)];
format = regexprep(format,'\\t','&');

% Open table file
fid = fopen(filename, 'w');
if contains(filename, "Table_E1")
    
    % Frontmatter
    fprintf(fid, '\t\t\t\\begin{tabular}{%s}\n', ['l' repmat('c',1,numDataCols) ]);
    
    % Toprule
    fprintf(fid, '\t\t\t\t\\toprule\n');
    
    % Meta-column headers
    numHeaderRows = length(metaheader);
    for i = 1:numHeaderRows
        fprintf(fid, metaheader{i});
    end
    
    % Column headers
    fprintf(fid, repmat('\t',1,5));
    for i = 1:numDataCols
        fprintf(fid, '&');
        fprintf(fid, '\\multicolumn{1}{c}{%s}', colHeaders{i});
        
        if i == numDataCols
            fprintf(fid, '\\\\\n');
        end
    end
    
    % Units, below column headers
    fprintf(fid, repmat('\t',1,5));
    for i = 1:numDataCols
        fprintf(fid, '&');
        fprintf(fid, '\\multicolumn{1}{c}{%s}', untHeaders{i});
        
        if i == numDataCols
            fprintf(fid, '\\\\\n');
        end
    end
    
    % Column numbers 
    fprintf(fid, repmat('\t',1,5));
    for i = 1:numDataCols
        fprintf(fid, '&');
        fprintf(fid, '\\multicolumn{1}{c}{(%d)}', i);
        
        if i == numDataCols
            fprintf(fid, '\\\\\n');
        end
    end
    
    % Midrule
    fprintf(fid, '\t\t\t\t\t\\midrule\n');
end 

% Write data rows
for i = 1:numDataRows
    fprintf(fid, ['\t\t\t\t\t' format '\\\\ \n'], rowNames{i}, table{i,:}{:});
end

if contains(filename, "Table_E1")
    % Footer
    fprintf(fid, '\t\t\t\t\t\\bottomrule\n');
    fprintf(fid, '\t\t\t\\end{tabular}\n');
    fprintf(1,'Written summary statistics table to %s\n', filename);
end
end